import { useMutation } from '@tanstack/react-query';
import cn from 'classnames';
import { FC } from 'react';
import { useNavigate } from 'react-router-dom';

import { AuthService } from '../../../services/auth.service.ts';
import useAuthStore from '../../../zustand/stores/useAuthStore.ts';

import type { LogoutProps } from './Logout.props';

const Logout: FC<LogoutProps> = () => {
  const { isLogged, logout } = useAuthStore();
  const navigate = useNavigate();

  const { mutate } = useMutation({
    mutationKey: ['logout'],
    mutationFn: () => AuthService.logout(),
    onSuccess() {
      logout();
      navigate('/auth');
    },
  });

  return (
    <>
      {isLogged() && (
        <button
          className={cn('text-[.8em]')}
          onClick={() => {
            mutate();
          }}
        >
          Выйти
        </button>
      )}
    </>
  );
};

export default Logout;
